/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.cmd.entity;

import cn.easyplatform.entities.beans.project.ProjectBean;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.dao.Page;
import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.vos.EntityVo;
import cn.easyplatform.studio.vos.QueryResultVo;

import java.util.List;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class QueryCmd implements Command<QueryResultVo> {

	private String type;

	private String field;

	private String value;

	private int pageSize;

	public QueryCmd(int pageSize) {
		this.pageSize = pageSize;
	}

	public QueryCmd(String type, int pageSize) {
		this(type, null, null, pageSize);
	}

	public QueryCmd(String field, String value, int pageSize) {
		this(null, field, value, pageSize);
	}

	public QueryCmd(String type, String field, String value, int pageSize) {
		this.type = type;
		this.field = field;
		this.value = value;
		this.pageSize = pageSize;
	}

	@Override
	public QueryResultVo execute(CommandContext cc) {
		ProjectBean pb = cc.getProject();
		StringBuilder sb = new StringBuilder(
				"select entityId,name,desp,type,subType from ");
		sb.append(pb.getEntityTableName()).append(" where 1=1");
		if (!Strings.isBlank(type)) {
			String[] types = type.split(",");
			if (types.length == 1)
				sb.append(" and type='").append(type).append("'");
			else {
				sb.append(" and type in(");
				for (int i = 0; i < types.length; i++) {
					sb.append("'").append(types[i]).append("'");
					if (i < types.length - 1)
						sb.append(",");
				}
				sb.append(")");
			}
		}
		String[] params = new String[0];
		if (!Strings.isBlank(value)) {
			if (field.equals("*")) {
				params = new String[3];
				params[0] = "%" + value + "%";
				params[1] = "%" + value + "%";
				params[2] = "%" + value + "%";
				sb.append(" and (entityId like ? or name like ? or desp like ?)");
			} else if (value.indexOf(",") < 0) {
				params = new String[1];
				params[0] = "%" + value + "%";
				sb.append(" and ").append(field).append(" like ?");
			} else {
				params = value.split(",");
				sb.append(" and ").append(field).append(" in (");
				for (int i = 0; i < params.length; i++) {
					sb.append("?");
					if (i < params.length - 1)
						sb.append(",");
				}
				sb.append(")");
			}
		}
		Page page = null;
		if (pageSize > 0) {
			page = new Page(pageSize);
			page.setOrderBy("entityId");
		}
		List<EntityVo> data = cc.getEntityDao().selectList(sb.toString(), page,
				params);
		return new QueryResultVo(page == null ? 0 : page.getTotalCount(), data);
	}
}
